package com.beimihu.lianxi;

public class MergeSort {
    public static void mergeSort(int[] arr) {
        if (arr.length > 1) {
            int mid = arr.length / 2;
            int[] left = new int[mid];
            int[] right = new int[arr.length - mid];

            for (int i = 0; i < mid; i++) {
                left[i] = arr[i];
            }
            for (int j = mid; j < arr.length; j++) {
                right[j - mid] = arr[j];
            }

            mergeSort(left);
            mergeSort(right);

            merge(arr, left, right);
        }
    }

    private static void merge(int[] arr, int[] left, int[] right) {
        int leftLen = left.length;
        int rightLen = right.length;
        int i = 0, j = 0, k = 0;

        while (i < leftLen && j < rightLen) {
            if (left[i] <= right[j]) {
                arr[k] = left[i];
                i++;
            } else {
                arr[k] = right[j];
                j++;
            }
            k++;
        }

        while (i < leftLen) {
            arr[k] = left[i];
            i++;
            k++;
        }

        while (j < rightLen) {
            arr[k] = right[j];
            j++;
            k++;
        }
    }
}
